package com.developer.fans.upgrader;

import android.util.Log;

import com.coocaa.x.framework.utils.Storage;
import com.developer.fans.CrackApplication;
import com.duowan.mobile.netroid.Listener;
import com.duowan.mobile.netroid.NetroidError;
import com.duowan.mobile.netroid.Network;
import com.duowan.mobile.netroid.RequestQueue;
import com.duowan.mobile.netroid.cache.DiskCache;
import com.duowan.mobile.netroid.stack.HurlStack;
import com.duowan.mobile.netroid.toolbox.BasicNetwork;
import com.duowan.mobile.netroid.toolbox.FileDownloader;

import org.apache.http.protocol.HTTP;

import java.io.File;
import java.io.IOException;

/**
 * Created by lu on 15-8-11.
 */
public class Downloader {
    public static interface LiteUpgradeDownloaderListener {
        void onStart();

        void onProgress(int percent, long downloaded_length, long file_length);

        void onCancel();

        void onError();

        void onSuccess(String apk_file);
    }

    private static Downloader instance = new Downloader();

    public static Downloader getInstance() {
        return instance;
    }

    private static final int TASK_SIZE = 2;
    private FileDownloader filedownloader = null;
    private RequestQueue mQueue = null;
    private LiteUpgradeDownloaderListener listener = null;
    private FileDownloader.DownloadController dc = null;
    private String save_path = null;

    private String save_file = null;

    private Downloader() {
        Network network = new BasicNetwork(new HurlStack("superx.cn", null), HTTP.UTF_8);
        mQueue = new RequestQueue(network, TASK_SIZE, new DiskCache(new File(CrackApplication.getContext().getCacheDir(), "cache")));
        mQueue.start();
        filedownloader = new FileDownloader(mQueue, 1);
        save_path = _getSavePath() + "/";
    }

    private String _getSavePath() {
        File file = CrackApplication.getContext().getExternalCacheDir();
        if (file != null && Storage.getFreeSpace(file.getAbsolutePath(), true) > 50 * 1024 * 1024) {
            file = new File(file.getAbsolutePath() + "/download");
            try {
                Runtime.getRuntime().exec("chmod -R 777 " + CrackApplication.getContext().getExternalCacheDir().getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            file = new File(CrackApplication.getContext().getCacheDir().getAbsolutePath() + "/download");
            try {
                Runtime.getRuntime().exec("chmod -R 777 " + CrackApplication.getContext().getCacheDir().getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (!file.exists())
            file.mkdirs();
        try {
            Runtime.getRuntime().exec("chmod -R 777 " + file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

    public void setListener(LiteUpgradeDownloaderListener l) {
        listener = l;
    }

    public synchronized void start(final String fileName, final String url) {
        CrackApplication.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.i("upgrade", "LiteUpgradeDownloader dc:" + dc + "   save_path:" + save_path + "   url:" + url);
                if (dc == null) {
                    save_file = new StringBuilder(save_path).append(fileName).toString();
                    dc = getFileDownload().add(save_file, url, myListener);
                } else {
                    dc.resume();
                }
            }
        });
    }

    public synchronized void cancel() {
        if (dc != null)
            dc.discard();
    }

    public synchronized int getStatus() {
        return dc.getStatus();
    }

    private Listener<Void> myListener = new Listener<Void>() {

        @Override
        public void onPreExecute() {
            Log.i("upgrade", "onPreExecute");
            try {
                if (listener != null)
                    listener.onStart();
            } catch (Exception e) {
            }
        }

        @Override
        public void onError(final NetroidError error) {
            Log.i("upgrade", "onError");
            try {
                if (listener != null)
                    listener.onError();
            } catch (Exception e) {
            }
            dc = null;
        }

        @Override
        public void onCancel() {
            Log.i("upgrade", "onCancel");
            try {
                if (listener != null)
                    listener.onCancel();
            } catch (Exception e) {
            }
            dc = null;
        }

        @Override
        public void onProgressChange(final long fileSize, final
        long downloadedSize) {
            Log.i("upgrade", "onProgressChange:" + (int) (downloadedSize * 100 / fileSize) + "%     " + downloadedSize + "/" + fileSize);
            try {
                if (listener != null)
                    listener.onProgress((int) (downloadedSize * 100 / fileSize), downloadedSize, fileSize);
            } catch (Exception e) {
            }
        }

        @Override
        public void onSuccess(Void aVoid) {
            Log.i("upgrade", "onSuccess");
            try {
                Runtime.getRuntime().exec("chmod -R 755 " + save_path);
            } catch (Exception e) {
            }
            try {
                if (listener != null)
                    listener.onSuccess(save_file);
            } catch (Exception e) {
            }
            dc = null;
        }
    };

    private FileDownloader getFileDownload() {
        return filedownloader;
    }
}
